<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>添加进车订单</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
  <link rel="stylesheet" href="${pageContext.request.contextPath}/css/purchase.css">
  <link rel="stylesheet" href="${pageContext.request.contextPath}/css/salesman/salesmannew.css">
</head>
<body>
<!-- 顶部导航 -->
<header class="dashboard-header">
  <div class="container">
    <div class="d-flex justify-content-between align-items-center">
      <div>
        <h1 class="h3 mb-0"><i class="bi bi-bicycle"></i> 电动车销售管理系统</h1>
        <p class="mb-0 opacity-75">业务员工作台</p>
      </div>
      <div class="d-flex align-items-center">
        <div class="me-3">
          <span class="d-none d-md-inline">${currentUser.name}</span>
          <div class="badge bg-light text-dark">
            <i class="bi bi-person-circle me-1"></i> 业务员
          </div>
        </div>
        <div class="dropdown">
          <button class="btn btn-light rounded-circle p-1" type="button" data-bs-toggle="dropdown">
            <i class="bi bi-gear fs-5"></i>
          </button>
          <ul class="dropdown-menu dropdown-menu-end">
            <li><a class="dropdown-item" href="${pageContext.request.contextPath}/changePassword"><i class="bi bi-lock me-2"></i> 修改密码</a></li>
            <li><hr class="dropdown-divider"></li>
            <li><a class="dropdown-item text-danger" href="logout"><i class="bi bi-box-arrow-right me-2"></i> 退出登录</a></li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</header>

<div class="container py-4">
  <!-- 面包屑导航 -->
  <nav aria-label="breadcrumb" class="mb-4">
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="${pageContext.request.contextPath}/purchase/list">进车订单管理</a></li>
      <li class="breadcrumb-item active" aria-current="page">添加新订单</li>
    </ol>
  </nav>

  <div class="form-container">
    <div class="d-flex justify-content-between align-items-center mb-4">
      <div>
        <h2 class="mb-0"><i class="bi bi-plus-lg me-2 text-primary"></i>添加新订单</h2>
        <p class="text-muted mb-0">创建新的电动车采购订单</p>
      </div>
      <div>
        <a href="${pageContext.request.contextPath}/purchase/list" class="btn btn-light">
          <i class="bi bi-arrow-left me-1"></i> 返回列表
        </a>
      </div>
    </div>

    <!-- 错误消息提示 -->
    <c:if test="${not empty errorMessage}">
      <div class="alert alert-danger alert-dismissible fade show mb-4" role="alert">
        <i class="bi bi-exclamation-triangle me-2"></i> ${errorMessage}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
      </div>
    </c:if>

    <form action="${pageContext.request.contextPath}/purchase/save" method="post" id="purchaseForm">
      <div class="mb-4">
        <h5 class="mb-3"><i class="bi bi-bicycle me-2"></i>选择车辆</h5>

        <div class="mb-3">
          <div class="form-text">点击下方车辆进行选择</div>
        </div>

        <div id="vehicleOptions">
          <c:forEach items="${vehicles}" var="vehicle">
            <div class="vehicle-option" data-id="${vehicle.id}" data-price="${vehicle.price}">
              <div class="d-flex align-items-center">
                <img src="${pageContext.request.contextPath}/images/vehicles/${vehicle.pic}"
                     class="vehicle-img" alt="${vehicle.brand}">
                <div class="flex-grow-1">
                  <h6 class="mb-1">${vehicle.brand} ${vehicle.model}</h6>
                  <div class="d-flex text-muted small mb-1">
                    <span class="me-3"><i class="bi bi-palette"></i> ${vehicle.color}</span>
                    <span><i class="bi bi-calendar"></i> ${vehicle.productionYear}年款</span>
                  </div>
                  <div class="fw-bold text-primary">¥${vehicle.price}</div>
                </div>
                <div class="form-check">
                  <input class="form-check-input" type="radio" name="vehicleId"
                         id="vehicle_${vehicle.id}" value="${vehicle.id}" style="transform: scale(1.5);">
                </div>
              </div>
            </div>
          </c:forEach>

          <c:if test="${empty vehicles}">
            <div class="alert alert-warning">
              <i class="bi bi-exclamation-circle me-2"></i> 没有可用的车辆信息，请联系管理员添加车辆
            </div>
          </c:if>
        </div>
      </div>

      <div class="mb-4">
        <h5 class="mb-3"><i class="bi bi-123 me-2"></i>采购数量</h5>

        <div class="d-flex align-items-center">
          <div class="quantity-control me-4">
            <button type="button" class="btn btn-light border" id="decreaseBtn">
              <i class="bi bi-dash"></i>
            </button>
            <input type="number" class="form-control" id="quantity" name="quantity" value="1" min="1" max="100" readonly>
            <button type="button" class="btn btn-light border" id="increaseBtn">
              <i class="bi bi-plus"></i>
            </button>
          </div>

          <div class="d-flex align-items-center">
            <div class="text-muted me-2">总价:</div>
            <div class="h4 mb-0 text-primary" id="totalPrice">¥0</div>
          </div>
        </div>
      </div>

      <div class="d-flex justify-content-end mt-5 pt-3 border-top">
        <button type="submit" class="btn btn-primary w-100 py-3" id="submitBtn">
          <i class="bi bi-check-lg me-2"></i> 提交订单
        </button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
  // 车辆选择功能
  document.querySelectorAll('.vehicle-option').forEach(option => {
    const radio = option.querySelector('input[type="radio"]');

    // 点击整个区域选择车辆
    option.addEventListener('click', function(e) {
      // 如果点击的是单选按钮，不处理（避免重复）
      if (e.target.tagName === 'INPUT') return;

      // 选择当前车辆
      radio.checked = true;

      document.querySelectorAll('.vehicle-option').forEach(opt => {
        opt.classList.remove('selected');
      });
      this.classList.add('selected');

      // 计算总价
      calculateTotalPrice();
    });

    radio.addEventListener('change', function() {
      if (this.checked) {
        document.querySelectorAll('.vehicle-option').forEach(opt => {
          opt.classList.remove('selected');
        });
        option.classList.add('selected');
        calculateTotalPrice();
      }
    });
  });

  // 数量控制
  const quantityInput = document.getElementById('quantity');
  const decreaseBtn = document.getElementById('decreaseBtn');
  const increaseBtn = document.getElementById('increaseBtn');

  decreaseBtn.addEventListener('click', function() {
    let currentValue = parseInt(quantityInput.value);
    if (currentValue > 1) {
      quantityInput.value = currentValue - 1;
      calculateTotalPrice();
    }
  });

  increaseBtn.addEventListener('click', function() {
    let currentValue = parseInt(quantityInput.value);
    if (currentValue < 100) {
      quantityInput.value = currentValue + 1;
      calculateTotalPrice();
    }
  });

  // 计算总价
  function calculateTotalPrice() {
    const selectedOption = document.querySelector('.vehicle-option.selected');
    if (!selectedOption) {
      document.getElementById('totalPrice').textContent = '¥0';
      return;
    }

    const price = parseFloat(selectedOption.getAttribute('data-price'));
    const quantity = parseInt(quantityInput.value);
    const totalPrice = price * quantity;

    document.getElementById('totalPrice').textContent = '¥' + totalPrice.toFixed(2);
  }

  // 表单提交验证
  document.getElementById('purchaseForm').addEventListener('submit', function(e) {
    const selectedVehicle = document.querySelector('input[name="vehicleId"]:checked');

    if (!selectedVehicle) {
      e.preventDefault();
      alert('请选择要采购的车辆！');
      return false;
    }

    return true;
  });

  // 页面加载时初始化
  document.addEventListener('DOMContentLoaded', function() {
    // 如果有默认选择的车辆，计算总价
    const defaultSelected = document.querySelector('input[name="vehicleId"]:checked');
    if (defaultSelected) {
      defaultSelected.closest('.vehicle-option').classList.add('selected');
      calculateTotalPrice();
    }
  });

  // 消息自动消失
  setTimeout(() => {
    const messages = document.querySelectorAll('.message');
    messages.forEach(msg => {
      msg.style.opacity = '0';
      setTimeout(() => msg.style.display = 'none', 300);
    });

    // 发送 AJAX 请求，通知服务器清空消息
    fetch('${pageContext.request.contextPath}/ClearMessageServlet', {
      method: 'GET',
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    });
  }, 3000);
</script>
</body>
</html>